<template>
  <div class="manage">
    <el-card class="search-top">
      <!-- 顶部操作栏 -->
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="用户昵称" prop="keywords">
                <el-input
                    v-model="queryParams.user.username"
                    placeholder="用户昵称"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用户账号" prop="keywords" label-width="80px">
                <el-input
                    v-model="queryParams.user.userAcct"
                    placeholder="用户账号"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号" prop="keywords" label-width="80px">
                <el-input
                    v-model="queryParams.user.phone"
                    placeholder="手机号"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="状态" prop="status" label-width="80px">
                <el-select
                    v-model="queryParams.user.status"
                    placeholder="全部"
                    clearable
                    class="!w-[100px]"
                    style="width: 200px"
                >
                  <el-option label="待激活" :value="0"/>
                  <el-option label="正常" :value="1"/>
                  <el-option label="禁用" :value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间" label-width="80px">
                <el-date-picker
                    v-model="queryParams.createTime"
                    :editable="false"
                    class="!w-[240px]"
                    type="daterange"
                    range-separator="~"
                    start-placeholder="开始时间"
                    end-placeholder="截止时间"
                    value-format="YYYY-MM-DD"
                    style="width: 240px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="80px" style="margin-left:25px">
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              </el-form-item>

            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>


    <el-card shadow="never" class="search-table">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog('insert',undefined)">
            新增
          </el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete()" :disabled="flag">
            删除
          </el-button>
        </div>
        <div>
          <el-button type="primary" icon="download" @click="downloadExcel">
            下载模板
          </el-button>
          <el-button icon="upload" @click="handleOpenImportDialog">
            导入
          </el-button>
          <el-button icon="download" @click="handleExport">
            导出
          </el-button>
        </div>
      </div>
      <!-- 菜单表格 -->
      <div class="common-table">
        <!-- 用户数据Table -->
        <el-table :data="tableData" @selection-change="handleSelectionChange" stripe style="width: 100%"
                  max-height="300px" v-loading="loading">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="头像" align="center">
            <template #default="scope">
              <el-image :src="scope.row.imgPath" :alt="scope.row.username" style="width: 50px; height: 50px;"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名称" width="100px" align="center"/>
          <el-table-column prop="userAcct" label="用户账号" align="center" width="100px"/>
          <el-table-column prop="sex" label="性别" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.sex === 'O'">保密</el-tag>
              <el-tag v-else-if="scope.row.sex === 'M'">男</el-tag>
              <el-tag v-else>女</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="250px" show-overflow-tooltip align="center"/>
          <el-table-column prop="phone" label="手机号" width="150px" align="center"/>
          <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '0'" type="info">待激活</el-tag>
              <el-tag v-else-if="scope.row.status === '1'" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="birthday" label="出生日期" align="center" width="110px">
          </el-table-column>
          <el-table-column prop="lastUpdateTime" label="最后操作时间" width="170px" align="center"/>
          <el-table-column fixed="right" align="center" label="操作" width="268">
            <template #default="scope">
              <el-button
                  type="primary"
                  link
                  size="small"
                  icon="RefreshLeft"
                  @click.stop="resetPassword(scope.row.userId)"
              >
                重置密码
              </el-button>
              <el-button
                  type="primary"
                  link
                  size="small"
                  icon="edit"
                  @click.stop="handleOpenDialog('detail',scope.row)"
              >
                详情
              </el-button>
              <el-button
                  type="primary"
                  link
                  size="small"
                  icon="edit"
                  @click.stop="handleOpenDialog('edit',scope.row)"
              >
                编辑
              </el-button>
              <el-button
                  type="danger"
                  link
                  size="small"
                  icon="delete"
                  @click.stop="handleDelete(scope.row.userId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pager">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 40]"
              :small="small"
              :disabled="disabled"
              :background="background"
              layout="->,total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    <el-dialog v-model="resetFlag" @close="resetCloseDialog" title="重置密码" style="width: 420px;height: 250px">
      <div><span>请输入该用户的新密码</span></div>
      <el-input v-model="newPassword" :disabled="!switchFlag" style="margin-top: 10px;margin-bottom: 10px"
                placeholder="请输入新密码" clearable/>
      <el-switch
          v-model="switchFlag"
          class="mb-2"
          size="large"
          inactive-text="是否输入密码"
          @change="switchChange"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="resetSubmit">确 定</el-button>
          <el-button @click="resetFlag = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加菜单对话框 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="45%"
        align-center
        @close="handleCloseDialog"
    >
      <el-form :disabled="disableFlag" ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="用户头像" prop="imgPath" v-if="dialog.type !== 'insert'">
          <el-upload
              v-model:file-list="importFormData.files"
              :show-file-list="false"
              :on-change="handleAvatarSuccess"
          >
            <img alt="formData.username" v-if="formData.imgPath" :src="formData.imgPath" style="width: 50px; height: 50px;" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名称" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名称" clearable/>
        </el-form-item>

        <el-form-item label="用户账号" prop="userAcct">
          <el-input v-model="formData.userAcct" placeholder="请输入用户账号" clearable/>
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="formData.sex" clearable placeholder="请选择性别" style="width: 130px">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="'0'">待激活</el-radio>
            <el-radio :value="'1'">正常</el-radio>
            <el-radio :value="'2'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" clearable placeholder="请输入手机号"/>
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select  v-model="formData.roleIds"  multiple  collapse-tags  collapse-tags-tooltip :max-collapse-tags="3"
                      placeholder="请选择角色" style="width: 340px"
          >
            <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="formData.birthday" type="date" placeholder="请选择日期"/>
        </el-form-item>

        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="formData.email" clearable placeholder="请输入用户邮箱"/>
        </el-form-item>
        <el-form-item label="用户地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入用户地址" clearable/>
        </el-form-item>
        <el-form-item label="个人简介" prop="personProfile" v-if="dialog.type !== 'insert'">
          <el-input v-model="formData.personProfile" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                    placeholder="请输入个人简介" clearable/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!disableFlag" type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteFlag" @close="deleteCloseDialog" center title="警告" style="width: 420px;height: 148px">
      <component class="icons" is="WarningFilled" style="width: 25px;height: 25px;color: #ff9a2e"/>
      <span> 确认删除用户?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="deleteSubmit">确 定</el-button>
          <el-button @click="deleteFlag = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <upload-user v-model="uploadDialogVisible"></upload-user>
  </div>
</template>

<script setup>
import UploadUser from "@/components/icons/UploadUser.vue";
import {ref, reactive, computed, onMounted} from 'vue';
import { Plus } from '@element-plus/icons-vue'
import {
  deleteByMenuId,
  deleteUser, downloadTemp, exportUserInfo,
  getAllMenu,
  getMenuById, getRoles,
  getUserByPage, insertUser,
  resetUserPassword,
  updateUser
} from "@/api/index.js";
import {ElMessage} from "element-plus";
import IconsSelect from "@/components/icons/iconsSelect.vue";
import axios from "axios";
import {getToken} from "@/utils/cookies.js";
import http from "@/utils/request.js";

const uploadDialogVisible = ref(false);

// 模拟菜单数据
const tableData = ref([]);

const loading = ref(false);
const switchFlag = ref(false);
// 搜索关键字
const searchKey = ref('');
// 当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10);
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const total = ref(0);
const newPassword = ref("123456a");
const resetUserId = ref();
const disableFlag = ref(false);
const menuFormRef = ref(null);
const flag = ref(true);
const roleOptions = ref();
// 初始菜单表单数据
const initialMenuFormData = ref({
  imgPath: null,
  username: null,
  userAcct: null,
  sex: 'O',
  email: null,
  phone: null,
  status: '0',
  birthday: null,
  address: null,
  personProfile: null,
  roleIds: []
});

const rules = reactive({
  username: [{required: true, message: "请输入用户名称", trigger: "blur"}],
  userAcct: [{required: true, message: "请输入用户账户", trigger: "blur"}],
  sex: [{required: true, message: "请选择用户性别", trigger: "change"}],
  status: [{required: true, message: "请选择用户状态", trigger: "change"}],
  phone: [{required: true, message: "请输入手机号", trigger: "blur"}],
});

const options = reactive([
  {
    value: 'O',
    label: '保密',
  },
  {
    value: 'M',
    label: '男',
  },
  {
    value: 'W',
    label: '女',
  }
]);
const formData = ref({...initialMenuFormData.value});

// 存储选中项的 id 数组
const selectIds = ref([]);
const dialog = reactive({
  title: '编辑菜单',
  visible: false,
  type: 'edit'
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  createTime: [],
  user: {
    username: null,
    userAcct: null,
    phone: null,
    status: null,
  }
});

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  queryParams.pageSize = pageSize.value;
  handleQuery();
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  queryParams.pageNum = currentPage.value;
  handleQuery();
};

const handleQuery = () => {
  console.log('搜索');
  queryParams.user.startDate = queryParams.createTime[0];
  queryParams.user.endDate = queryParams.createTime[1];
  getUserByPage(queryParams).then((data) => {
    if (data.data.code === 200) {
      console.log(data.data.data)
      tableData.value = data.data.data.records;
      total.value = data.data.data.total;
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  }).finally(() => {
    loading.value = false;
  });
};
const resetFlag = ref(false);
const resetPassword = (userId) => {
  resetUserId.value = userId;
  resetFlag.value = true;
}

const resetSubmit = () => {
  //重置密码调用后端
  resetUserPassword({userId: resetUserId.value, password: newPassword.value}).then((data) => {
    if (data.data.code === 200) {
      ElMessage.success(data.data.msg);
      resetFlag.value = false;
      resetUserId.value = null;
      newPassword.value = "123456a";
      switchFlag.value = false;
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  })
}
const resetCloseDialog = () => {
  resetFlag.value = false;
  newPassword.value = "123456a";
  resetUserId.value = null;
  switchFlag.value = false;
}

const switchChange = () => {
}

onMounted(() => {
  handleQuery();
})


const handleResetQuery = () => {
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.createTime = [];
  queryParams.user.username = null;
  queryParams.user.userAcct = null;
  queryParams.user.phone = null;
  queryParams.user.status = null;
  pageSize.value = 10;
  currentPage.value = 1;
  handleQuery();
}

const handleCloseDialog = () => {
  resetForm();
  disableFlag.value = false;
  dialog.visible = false;
};

const resetForm = () => {
  // menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value = {
    imgPath: null,
    username: null,
    userAcct: null,
    sex: 'O',
    email: null,
    phone: null,
    status: '0',
    birthday: null,
    address: null,
    personProfile: null,
    roleIds: []
  };
};
const importFormData = {
  files: []
};

const handleOpenDialog = async (type, row) => {
  try {
    const data = await getRoles();
    roleOptions.value = data.data.data;
    if (type === 'edit') {
      dialog.visible = true;
      dialog.title = "编辑用户"
      dialog.type = "edit"
      initialMenuFormData.value = {...row};
      formData.value = {...row};
    } else if (type === 'insert') {
      dialog.visible = true;
      dialog.title = "新增用户"
      dialog.type = "insert"
    } else if (type === 'detail') {
      dialog.visible = true;
      dialog.title = "用户详情"
      dialog.type = "detail"
      disableFlag.value = true;
      initialMenuFormData.value = {...row};
      formData.value = {...row};
    }
  }catch (error) {
    console.error('获取角色选项时出错:', error);
    ElMessage.error("获取角色选项时出错")
  }
};

const handleSubmit = async () => {
  if (!menuFormRef.value) return;
  try {
    // 进行表单验证
    const valid = await menuFormRef.value.validate();
    if (valid) {
      // 表单验证通过，调用 updateUser 方法更新用户信息
      let data;
      if (dialog.type === "insert") {
        data = await insertUser(formData.value);
      } else if (dialog.type === "edit") {
        const fm = new FormData();
        if (importFormData.files[0]) {
          fm.append('file', importFormData.files[0].raw);
        }
        fm.append('user', JSON.stringify(formData.value));
        data = await updateUser(fm);
      }
      if (data && data.data.code === 200) {
        // 更新成功，给出成功提示，关闭对话框并重新查询数据
        ElMessage.success(data.data.msg);
        handleCloseDialog();
        handleQuery();
      } else {
        // 更新失败，给出失败提示
        ElMessage.error(data.data.msg);
      }
    } else {
      // 表单验证失败，输出日志
      console.log("表单校验失败");
    }
  } catch (error) {
    // 捕获并输出详细的错误信息，给出通用错误提示
    console.error("执行提交操作时出现错误:", error);
    ElMessage.error("执行异常");
  }
};

const deleteUserId = ref();
const deleteFlag = ref(false);
const handleDelete = (userId) => {
  deleteUserId.value = [userId || selectIds.value].join(",")
  console.log(deleteUserId.value)
  deleteFlag.value = true;
};

const deleteCloseDialog = () => {
  deleteUserId.value = null;
  deleteFlag.value = false;
}

const deleteSubmit = (userId) => {
  deleteUser(deleteUserId.value).then((data) => {
    if (data.data.code === 200) {
      ElMessage.success(data.data.msg);
      deleteCloseDialog();
      handleQuery()
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  })
}


const handleSelectionChange = (selection) => {
  selectIds.value = selection.map((item) => item.userId);
  flag.value = selectIds.value.length === 0;
  console.log('选中项的 ID:', selectIds.value);
};


function handleOpenImportDialog() {
  uploadDialogVisible.value = true;
}

const downloadExcel = async () => {
  downloadTemp().then((response) => {
    const base64Data = response.data.data;
    const byteCharacters = atob(base64Data);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    const blob = new Blob([byteArray], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'template.xlsx';
    a.click();
    URL.revokeObjectURL(url);
  }).catch(() => {
    ElMessage.error("执行异常")
  })
}

const handleExport = () => {
  queryParams.user.startDate = queryParams.createTime[0];
  queryParams.user.endDate = queryParams.createTime[1];
  exportUserInfo(queryParams).then((data) => {
    if (data.data.code === 200) {
      const base64Data = data.data.data;
      const byteCharacters = atob(base64Data);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '用户信息表.xlsx';
      a.click();
      URL.revokeObjectURL(url);
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  })
}

const handleAvatarSuccess = (file) => {
  console.log(file.raw.type)
  const isJpgOrPng = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('请上传 JPEG 或 PNG 格式的图片');
    return false
  }
  const isLt2M = file.raw.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
    return false
  }
  if (file.raw) {
    formData.value.imgPath = URL.createObjectURL(file.raw);
  }
}

</script>

<style scoped>
.manage {
  height: 80%;

  .search-table {
    box-shadow: var(--el-box-shadow-light);
  }

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    height: 80%;
    position: relative;
    margin-top: 10px;

    .pager {
      position: relative;
      top: 10px;
      bottom: 0;
    }
  }
}


.search-top {
  margin-bottom: 10px;
}

.flex-x-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>